package com.ayh.campusfun.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.ayh.campusfun.common.core.email.EmailService;
import com.ayh.campusfun.common.core.jwt.JWTUtils;
import com.ayh.campusfun.common.exception.http.CaptchaCodeException;
import com.ayh.campusfun.common.exception.http.PasswordOrUserErrorException;
import com.ayh.campusfun.common.service.impl.BaseServiceImpl;
import com.ayh.campusfun.common.utils.Validator;
import com.ayh.campusfun.dao.UsersDao;
import com.ayh.campusfun.dto.LoginForOtherDTO;
import com.ayh.campusfun.dto.RegisterDTO;
import com.ayh.campusfun.entity.Users;
import com.ayh.campusfun.service.UsersService;
import org.apache.axis.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户表(Users)表服务实现类
 *
 * @author ayh
 * @since 2021-03-20 20:42:07
 */
@Service
public class UsersServiceImpl extends BaseServiceImpl<Users> implements UsersService {
    @Resource
    private UsersDao usersDao;

    @Autowired
    private JWTUtils jwtUtils;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private EmailService emailService;


    @Override
    public Map<String, Object> login(String account, String password, String captchaKey, String captchaCode) {
        String captcha = (String) redisTemplate.opsForValue().get(captchaKey);
        redisTemplate.delete(captchaKey);
        if (StringUtils.isEmpty(captcha)) {
            throw new CaptchaCodeException(60005);
        }
        if (!captcha.equals(captchaCode)) {
            throw new CaptchaCodeException(60004);
        }
        Users user = new Users();
        if (Validator.isEmail(account)) {
            user.setEmail(account);
            user.setUid(null);
        }else if (Validator.isMobile(account)) {
            user.setPhone(account);
        } else {
            user.setUid(account);
        }
        user.setPassword(password);
        Users findUser = usersDao.findUserByUser(user);
        if(null == findUser) {
            throw new PasswordOrUserErrorException(60006);
        }
        if (!findUser.getPassword().equals(password)) {
            throw new PasswordOrUserErrorException(60006);
        }
        user.setUid(findUser.getUid());
        user.setAvatarUrl(findUser.getAvatarUrl());
        user.setNickName(findUser.getNickName());
        String token = jwtUtils.getToken(user);
        findUser.setPassword(null);
        redisTemplate.opsForValue().set(token,user,3,TimeUnit.DAYS);
        Map<String, Object> map = new HashMap<>();
        map.put("user", findUser);
        map.put("token",token);
        return map;
    }

    @Override
    public Long register(RegisterDTO registerDTO) {
        String codeKey = (String) redisTemplate.opsForValue().get(registerDTO.getEmail());
        if (StringUtils.isEmpty(codeKey)){
            throw new CaptchaCodeException(60005);
        }
        if (!codeKey.equals(registerDTO.getAuthCode())){
            throw new CaptchaCodeException(60004);
        }
        Users users = new Users();
        BeanUtils.copyProperties(registerDTO,users);
        String uid = RandomUtil.randomString("1234567890",7);
        users.setUid(uid);
        users.setNickName(uid);
        Long insert = usersDao.insert(users);
//        String token = jwtUtils.getToken(users);
        redisTemplate.delete(registerDTO.getEmail());
        return insert;
    }

    @Override
    public String getAuthCode(String email) {
        String code = RandomUtil.randomString(4);
        redisTemplate.opsForValue().set(email, code, 3, TimeUnit.MINUTES);
        emailService.sendMail(email,"青春驿站-你的校园趣事匣子！","欢迎注册\"青春驿站\"，你的验证码为：" + code);
        return "success";
    }

    @Override
    public String refreshAuthCode(String email, String codeKey) {
        redisTemplate.delete(codeKey);
        return getAuthCode(email);
    }

    @Override
    public Map<String, Object> loginForOther(LoginForOtherDTO loginForOtherDTO) {
        Map<String, Object> map = new HashMap<>();
        map.put("openId",loginForOtherDTO.getOpenId());
        Users usersDaoByParam = usersDao.findByParam(map);
        if (null != usersDaoByParam){
            String token = jwtUtils.getToken(usersDaoByParam);
            usersDaoByParam.setPassword(null);
            redisTemplate.opsForValue().set(token,usersDaoByParam,3,TimeUnit.DAYS);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("user", usersDaoByParam);
            resultMap.put("token",token);
            return resultMap;
        }
        if (loginForOtherDTO.getLoginType().equals("qq")){
            Users users = Users.builder().nickName(loginForOtherDTO.getNickname())
                    .avatarUrl(loginForOtherDTO.getAvatarUrl())
                    .userAddress(loginForOtherDTO.getProvince() + "-" + loginForOtherDTO.getCity())
                    .sex(loginForOtherDTO.getGender().equals("男") ? 2 : 1)
                    .uid(RandomUtil.randomString("1234567890",7))
                    .openId(loginForOtherDTO.getOpenId())
                    .build();
            usersDao.insert(users);
            Users usersDaoById = usersDao.findById(users.getId());
            String token = jwtUtils.getToken(usersDaoById);
            usersDaoByParam.setPassword(null);
            redisTemplate.opsForValue().set(token,usersDaoByParam,3,TimeUnit.DAYS);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("user", usersDaoByParam);
            resultMap.put("token",token);
            return resultMap;
        }
        if (loginForOtherDTO.getLoginType().equals("weixin")){
            Users users = Users.builder().nickName(loginForOtherDTO.getNickname())
                    .avatarUrl(loginForOtherDTO.getAvatarUrl())
                    .userAddress(loginForOtherDTO.getProvince() + "-" + loginForOtherDTO.getCity())
                    .sex(loginForOtherDTO.getGender().equals("1") ? 2 : 1)
                    .uid(RandomUtil.randomString("1234567890",7))
                    .openId(loginForOtherDTO.getOpenId())
                    .build();
            usersDao.insert(users);
            Users usersDaoById = usersDao.findById(users.getId());
            String token = jwtUtils.getToken(usersDaoById);
            usersDaoByParam.setPassword(null);
            redisTemplate.opsForValue().set(token,usersDaoByParam,3,TimeUnit.DAYS);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("user", usersDaoByParam);
            resultMap.put("token",token);
            return resultMap;
        }
        return null;
    }

    @Override
    public List<Users> queryUserByParam(Map<String, Object> map) {
        return usersDao.queryUserByParam(map);
    }

    @Override
    public Users queryUserByUid(String uid) {
        return usersDao.queryUserByUid(uid);
    }

    @Override
    public void updateUserInfoById(Users users) {
        usersDao.updateUserInfoById(users);
        usersDao.updateUserInfoById1(users);
        usersDao.updateUserInfoById2(users);
        usersDao.updateUserInfoById3(users);
        usersDao.updateUserInfoById4(users);
        usersDao.updateUserInfoById5(users);
        usersDao.updateUserInfoById6(users);
        usersDao.updateUserInfoById7(users);
        usersDao.updateUserInfoById8(users);
        usersDao.updateUserInfoById9(users);
        usersDao.updateUserInfoById10(users);
        usersDao.updateUserInfoById11(users);
        usersDao.updateUserInfoById12(users);
    }

}
